package com.tater.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MonitorUtil {

    // rate 代表百分比 90 传入 0.9 即可  99 就是 0.99
    private    static long  getTP(List<MonitorMethod> methodInfos, double  rate){
        // 构建一个临时数组保存 满足1一分钟之内的数据
        List<MonitorMethod>  list = new ArrayList<>();
        // 计算最近一分钟的TP-rate
        long  endTime = System.currentTimeMillis();
        long  startTime = System.currentTimeMillis() - 60000;
        // 遍历列表集合
        int  length = methodInfos.size();
//        System.out.println(methodInfos.get(0).getMethodName()+"执行了 "+length+" 次");
        for (int i=0;i<length;i++){
            MonitorMethod  methodInfo = methodInfos.get(i);
            if (methodInfo.getEndTime() >= startTime && methodInfo.getEndTime() <= endTime){
                list.add(methodInfo);
            }
        }
        List<MonitorMethod> collect = list.stream().sorted(Comparator.comparing(MonitorMethod::getRunTime)).collect(Collectors.toList());
        int  index = (int)(collect.size() * rate);
        return collect.get(index).getRunTime();
    }

    public static void printTPInfo(Map<String,List<MonitorMethod>> map){
        System.out.println("########################"+ LocalDateTime.now().toString() +"#########################");
        for(Map.Entry<String,List<MonitorMethod>> methodInfos : map.entrySet()){
            System.out.println(methodInfos.getKey() +"的TP90:" + getTP(methodInfos.getValue(),0.9) + "毫秒,"
                    + "TP99:" + getTP(methodInfos.getValue(),0.99)+ "毫秒"+"-累计执行次数："+map.get(methodInfos.getKey()).size() );
        }
    }
}
